<template>
  <!--分配工人-->
  <el-dialog :close-on-click-modal="false" title="分配工人" width="70%" center :visible.sync="show"
             :before-close="closeThisDialog"
  >
    <el-row :gutter="40">
      <el-col :span="24">
        <el-table :data="tableData" size="mini" border stripe>
          <el-table-column width="200" align="center" prop="building_name" label="楼盘"></el-table-column>
          <el-table-column min-width="300" show-overflow-tooltip align="center" prop="workers_name" label="工人"></el-table-column>
        </el-table>
      </el-col>
      <el-col :span="15">
        <el-divider>楼盘</el-divider>
        <div style="text-align: center">
          <el-input style="width: 90%" clearable size="mini" placeholder="输入楼盘名字进行过滤" v-model="filterText">
          </el-input>
        </div>
        <el-tree style="max-height: 600px;overflow-y: auto"
                 :props="props"
                 :data="treeData"
                 accordion
                 node-key="id"
                 ref="tree"
                 show-checkbox
                 :filter-node-method="filterNode"
        >
            <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}</span>
                <el-tooltip v-if="data.is_leaf && data.works.length>0" effect="dark" content="点击可修改此楼盘员工"
                            placement="top"
                >
                  <el-button type="text" style="margin-left: 20px;color: red"
                             @click="editBuildingWork(data.id,data.works)"
                  >{{
                      data.works.map(item => {
                        return item.name
                      }).join(',')
                    }}</el-button>
                </el-tooltip>
            </span>
        </el-tree>
      </el-col>
      <el-col :span="9">
        <el-divider>分配工人</el-divider>
        <div style="text-align: center">
          <el-select v-model="works" value-key="id" size="mini" multiple placeholder="请选择工人" filterable>
            <el-option v-for="item in workList" :key="item.id" :value="item" :label="item.name"></el-option>
          </el-select>
          <el-checkbox v-model="allSelected" style="margin-left: 5px">选中所有工人</el-checkbox>
        </div>
      </el-col>
    </el-row>
    <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="closeThisDialog">关闭</el-button>
        <el-button size="mini" type="primary" @click="assignWorkers">分配</el-button>
        <el-button size="mini" type="primary" @click="saveAssignWorkers">保存分配</el-button>
      </span>
  </el-dialog>
</template>

<script>
import { listWorker } from '@/api/workOrder/workOrder'

export default {
  name: 'buildingTree',
  props: {
    show: {
      type: Boolean,
      default: false
    },
    treeData: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      filterText: '',
      props: {
        label: 'label',
        children: 'children',
        isLeaf: 'is_leaf'
      },
      works: [],
      workList: []
    }
  },
  computed: {
    allSelected: {
      get() {
        return this.works.length === this.workList.length
      },
      set(val) {
        if (val) {
          this.works = this.workList.map(item => {
            return Object.assign({}, item)
          })
        } else {
          this.works = []
        }
      }
    },
    tableData() {
      if (this.treeData && this.treeData.length) {
        let leafNode = this.getLeafNode(this.treeData[0])
        if (leafNode && leafNode.length) {
          return this.handleLeafNodeList(leafNode)
        } else {
          return []
        }
      }
      return []
    }
  },
  created() {
    this.initWorkerList()
  },
  methods: {
    /**
     * 改变所有的非叶子节点状态
     */
    changeAllNotLeafStatus(flag, data) {
      if (!data.is_leaf) {
        data.disabled = flag
        console.log(data)
      }
    },
    filterNode(value, data) {
      if (!value) {
        this.changeAllNotLeafStatus(false, data)
        return true
      } else {
        this.changeAllNotLeafStatus(true, data)
        return data.label.indexOf(value) !== -1
      }
    },
    editBuildingWork(nodeKey, worker) {
      this.works = worker.map(item => {
        return item
      })
      this.$refs.tree.setCheckedKeys([nodeKey])
    }, /**
     * 分配工人方法
     */
    assignWorkers() {
      const checkedNodes = this.$refs.tree.getCheckedNodes()
      if (checkedNodes.length <= 0) {
        this.$message.error('请选择楼盘')
        return
      }
      const leafNodes = checkedNodes.filter(item => item.is_leaf == true)
      leafNodes.forEach(item => {
        item.works = this.works.map(i => {
          return {
            id: i.id,
            name: i.name
          }
        })
      })
      this.works = []
      this.$refs.tree.setCheckedKeys([])
    },
    saveAssignWorkers() {
      let buildingWorkers = this.getLeafNodeWorkers(this.treeData[0])
      let flag = true
      buildingWorkers.forEach(item => {
        if (item.works.length == 0) {
          flag = false
        }
      })
      if (flag) {
        this.$emit('save', buildingWorkers)
      } else {
        this.$message.error('请将楼盘分配完')
      }
    },
    /**
     * 获取叶子节点的工人信息
     * @param node
     * @returns {*[]}
     */
    getLeafNodeWorkers(node) {
      let arr = []
      if (!node.is_leaf) {
        if (node.children.length > 0) {
          node.children.forEach(item => {
              let data = this.getLeafNodeWorkers(item)
              if (data) {
                if (Array.isArray(data)) {
                  arr = arr.concat(data)
                } else {
                  arr.push(data)
                }
              }
            }
          )
          return arr
        }
      } else {
        let data = {
          id: node.id,
          works: node.works
        }
        return data
      }
      return arr
    },
    initWorkerList() {
      listWorker().then(res => {
        this.workList = res.data
      })
    },
    getLeafNode(node) {
      let arr = []
      if (!node.is_leaf) {
        if (node.children.length > 0) {
          node.children.forEach(item => {
              let data = this.getLeafNode(item)
              if (data) {
                if (Array.isArray(data)) {
                  arr = arr.concat(data)
                } else {
                  arr.push(data)
                }
              }
            }
          )
          return arr
        }
      } else {
        arr.push(node)
      }
      return arr
    },
    closeThisDialog() {
      this.$emit('close')
    },
    handleLeafNodeList(arr) {
      return arr.map(item => {
        return {
          building_name: item.label,
          workers_name: item.works.map(work => {
            return work.name
          }).join(',')
        }
      })
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  }
}
</script>

<style scoped>

</style>
